package com.means.polymerize.core.terminal.common.lang;

import lombok.SneakyThrows;

import javax.websocket.Session;
import java.nio.ByteBuffer;

/**
 * The type Web socket sender.
 *
 * @author xuhaifeng
 * @date 2021.05.09
 */
public record WebSocketSessionSender(Session session) {
    /**
     * 初始化Web套接字发送器
     * Instantiates a new Web socket sender.
     *
     * @param session the session
     * @param sink    the sink
     */
    public WebSocketSessionSender {
    }

    /**
     * 发送文本数据
     *
     * @param data the data
     */
    @SneakyThrows
    public synchronized void sendText(String data) {
        synchronized (session) {
            session.getAsyncRemote().sendText(data);
        }
    }

    /**
     * 发送字节数据
     *
     * @param data the data
     */
    @SneakyThrows
    public synchronized void sendByte(byte[] data) {
        synchronized (session) {
            session.getAsyncRemote().sendBinary(ByteBuffer.wrap(data));
        }
    }

    /**
     * 关闭会话
     */
    @SneakyThrows
    public synchronized void closeSession() {
        synchronized (session) {
            session.close();
        }
    }
}
